import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpReceive {
    public static void main(String[] args) {
        try {
            //)创建Socket对象
            //public DatagramSocket(int port)
            DatagramSocket ds = new DatagramSocket(10086);//接收端口号的消息
            while (true) {
                //2)创建一个接收容器:数据报包:DatagramPacket  实际数据没有这么大
                //public DatagramPacket(byte[] buf, int length)
                //自定义字节缓冲区
                byte[] bytes = new byte[1024];
                int lentgth = bytes.length;
                DatagramPacket dp = new DatagramPacket(bytes, lentgth);//建立信息包

                //3)public void receive(DatagramPacket p)
                ds.receive(dp);

                //4)解析实际数据
                //byte[] getData()   获取实际字节数
                //返回数据缓冲区。
                //int getLength()   获取实际长度
                byte[] bytes2 = dp.getData();
                int length2 = dp.getLength();
                String receiverStr = new String(bytes2, 0, length2);
                System.out.println("输入的数据为：" + receiverStr);

                //获取ip地址
                //InetAddress getAddress()
                //public String getHostAddress():
                String ip = dp.getAddress().getHostAddress();
                //展示数据
                System.out.println("data from " + ip);
            }
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //接收不关闭
            //接收socket对象一一直开着
        }
    }
}
